package fr.sharpe.app.earthvisualizationproject.controller.servers;

import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.ConnectException;
import java.rmi.Naming;
import java.rmi.RemoteException;

import com.mycila.event.api.Dispatcher;

import fr.sharpe.app.earthvisualizationdatamodel.services.RmiServices;

public class RmiServer {
	private String nameServer; // default localhost
	private int portServer; // default 1099
	private RmiServicesImpl services;
	private Dispatcher dispatcher;
	
	public RmiServer(String nameServer, int portServer, Dispatcher dispatcher) {
		this.nameServer = nameServer;
		this.portServer = portServer;
		this.dispatcher = dispatcher;
	}
	
	
	public void startService() {
		String serviceName = new String("EarthVisualisationService");
		try {
			
			this.services = new RmiServicesImpl(dispatcher);
			
			//--- take in place the RMI registry ---
			// case #1 :
			// into a specific (bash) console, use the command line 'rmiregistry'
			
			// or case #2:
			// Creates and exports a Registry instance on the local host (that uses custom socket factories for communication with that instance). [uncomment next line]
			 java.rmi.registry.LocateRegistry.createRegistry(1099);
			
			
			//--- starting the server ---
			
			// publication of services into the RMI registry :
			Naming.bind("rmi://localhost:"+1099+"/"+serviceName ,services);
			//Naming.rebind() is like bind but in overwrite mode!
			System.out.println("Service \""+serviceName+"\" is now available on server");
			
			
			// Some information concerning the RMI registry: [uncomment next 5 lines]
			/*
			java.rmi.registry.Registry reg = java.rmi.registry.LocateRegistry.getRegistry(nameServer, portServer);
			String[] namesServices = reg.list(); //names bound in this registry.
			System.out.println("List of service available on the server "+nameServer+":"+portServer);
			for(int i=0 ; i < namesServices.length ; i++)
				System.out.println("\t reg["+i+"]="+namesServices[i]);
			*/
		}
		catch (MalformedURLException e) {
			System.out.println("Whoops! java.net.MalformedURLException");
			System.out.println(e);
		}
		catch (ConnectException e) { // in particular when the RMI registry is not available
			System.out.println("Whoops! java.rmi.ConnectException");
			System.out.println(e);
		}
		catch (AlreadyBoundException e) { // service already bound into RMI registry
			System.out.println("Whoops! java.rmi.AlreadyBoundException");
			System.out.println(e);
		} 
		catch (RemoteException e) { 
			System.out.println("Whoops! java.rmi.RemoteException");
			System.out.println(e);
		}
		catch (java.lang.Exception e) { 
			System.out.println("Whoops! java.lang.Exception");
			System.out.println(e);
		}
	}
	
	public static void main(String args[]) {	
//		RmiServer peer = new RmiServer(null);
//		peer.startService();
//			
	}
}
